<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Userchildren;
use fast\Random;

/**
 * 首页接口
 */
class Index extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $jiami_url   = "http://39.105.29.86:8181/tool-sm2/encrypt";//加密接口
    protected $qianmi_url  = "http://39.105.29.86:8181/tool-sm2/sign";//签名接口
    protected $jiemi_url   = "http://39.105.29.86:8181/tool-sm2/decrypt";//解密接口
    protected $charset     = "utf-8";
    protected $version     = "1.0";
    protected $type        = 1;
//    protected $partner_id     = "200207776364";
    protected $param       = [];
    public function _initialize()
    {
        parent::_initialize();
        $this->param['version']         = $this->version;//接口版本
        $this->param['request_time']    = date('YmdHis');//请求时间
        $this->param['partner_id']      = input('partner_id');//合作者身份ID
        $this->param['_input_charset']  = $this->charset;//参数编码字符集
        $this->param['sign_type']       = "SM2";//签名类型
        if($this->type==2){
            $this->jiami_url   = "http://39.105.29.86:8282/tool-sm2/encrypt";//加密接口
            $this->qianmi_url  = "http://39.105.29.86:8282/tool-sm2/sign";//签名接口
            $this->jiemi_url   = "http://39.105.29.86:8282/tool-sm2/decrypt";//解密接口
//            $this->partner_id            = "200006503094";
        }else{

        }
    }


    public function ceshi(){
//        $url = "https://api.ku55.cn/index.php?s=/store/user/getChildLists&userId=645";
//
//        $ch          = curl_init($url);
//        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
////        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array (
//                'Content-Type: application/json',
//                //                'Content-Length: '.strlen($data_string),
//                'Access-Token:ba58f5c0f0ca1fdc0f02da9b7f6eacb6'
//            )
//        );
//        $result = json_decode(curl_exec($ch), true);
//        dump($result);exit();
//        $data = cache('data-');
//        $data = db('user_copy1')->select();
        $data = cache('data_two');

        foreach ($data as $k=>$v){
            $model = new Userchildren();
            $to_insert = [['member_id' => $v['parent_id'], 'level' => 1, 'children_id' => $v['id']]];
            $model->where('children_id', $v['parent_id'])->chunk(100000, function($items) use ($v, &$to_insert,$model) {
                foreach ($items as $item) {
                    $to_insert[] = [
                        'member_id' => $item->member_id,
                        'level' => $item['level'] + 1,
                        'children_id' => $v['id'],
                    ];
                }

                $model->insertAll($to_insert);
                $to_insert = [];
            },'level','asc');
            if (!empty($to_insert)) {
                $model->insertAll($to_insert);
            }
        }
       exit();

//        $data = cache('data_two');
//        $url = "https://api.ku55.cn/index.php?s=/store/user/list&page=1";
//        foreach ($data as $k=>$v){
//            $url .='&search='.$v['mobile'];
//            $ch          = curl_init($url);
//            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//    //        curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
//            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//            curl_setopt($ch, CURLOPT_HTTPHEADER, array (
//                    'Content-Type: application/json',
//                    //                'Content-Length: '.strlen($data_string),
//                    'Access-Token:ba58f5c0f0ca1fdc0f02da9b7f6eacb6'
//                )
//            );
//            $result = json_decode(curl_exec($ch), true);
//            $result = $result['data']['list']['data'][0];
//            $up['money'] = $result['balance'];
//            $up['golden'] = $result['golden'];
//            $up['silver'] = $result['silver'];
//            $up['gold'] = $result['gold'];
//            $up['invite_code'] = $result['invite_code'];
//            $up['platform'] = $result['platform'];
//            $up['user_json'] = json_encode($result,true);
//           $r=  db('user_copy1')->where(['id'=>$result['user_id']])->update($up);
//            dump($r);exit();
//        }
//        dump($data);
        exit();
        $num = 0;
        $inser = [];
//        dump($data['list']);exit();
        $this->digui($data['list']);

//        foreach ($data['list']['children'] as $k=>$v){
//            $inser['id'] = $v['user_id'];
//            $inser['parent_id'] = $v['parent_id'];
//            $inser['mobile'] = $v['mobile'];
//            $inser['nickname'] = $v['nick_name'];
//            $inser['level']  = $v['level'];
//            $inser['level_label']  = $v['level_label'];
//            $inser['group_id']  = 1;
//            $inser['salt']  = Random::alnum();
//            $inser['invitation_code'] = Random::alnum();
//            db('user_copy1')->insert($inser);
//            if(!empty($v['children'])){
//
//               $this->digui($v['children']);
//            }
//        }

//        dump($inser);
//        dump($num);
//        dump($data);
//        dump($result);
    }

    public function digui($data){
        if(!empty($data['children'])){
            foreach ($data['children'] as $k=>$v){
                $inser['id'] = $v['user_id'];
                $inser['parent_id'] = $v['parent_id'];
                $inser['mobile'] = $v['mobile'];
                $inser['nickname'] = $v['nick_name'];
                $inser['level']  = $v['level'];
                $inser['level_label']  = $v['level_label'];
                $inser['group_id']  = 1;
                $inser['salt']  = Random::alnum();
                $inser['invitation_code'] = Random::alnum();
//            dump($inser);
                db('user_copy1')->insert($inser);
                if(!empty($v['children'])){
                     $this->digui($v);
                }
            }
        }

    }


    public function img_url_to_base64($imgUrl)
    {
        $imageInfo = getimagesize($imgUrl);
        $imgUrl =  'data:' . $imageInfo['mime'] . ';base64,' . chunk_split(base64_encode(file_get_contents($imgUrl)));
//        echo '<img src="'.$imgUrl.'">';exit();
        return $imgUrl;
    }


    /**
     * 开设
     *
     */
    public function sc_register_merchant()
    {
        $data     = input('post.');
        $param    = $this->param;
        /****************业务参数***********************/
        $param['service']                    = "sc_register_merchant";//服务名称
        $param['request_no']                 = Random::numeric(32);//入网请求号
        $param['identity_id']                = $data['identity_id'];//子户在商户平台的用户id
        $param['merchant_type']              = "ENTERPRISE";//注册商户所属类型(参数传 英文值):
        $param['auth_protocol_no']           = Random::alnum(32);//用户授权协议流水号
        $param['auth_protocol_version']      = '1.0.0';//个人信息用户授权协议版本号，默认1.0.0
        $param['role_type']                  = 'ISSUER';//角色类型ISSUER：合作方 NORMAL：普通
        //身份证正面
//        $param['account_cert_pic1']          =  $this->img_url_to_base64($data['account_cert_pic1']);
//        //身份证反面
//        $param['account_cert_pic2']          = $this->img_url_to_base64($data['account_cert_pic2']);
//        //营业执照图片
//        $param['account_cert_pic3']          =  $this->img_url_to_base64($data['account_cert_pic3']);
//        //
//        $param['account_cert_pic4']          =  $this->img_url_to_base64($data['account_cert_pic4']);
//        //
//        $param['agree_pic']                  = $this->img_url_to_base64($data['agree_pic']);
        $param['account_cert_pic1']          = $data['account_cert_pic1'];
        //身份证反面
        $param['account_cert_pic2']          = $data['account_cert_pic2'];
        //营业执照图片
        $param['account_cert_pic3']          =  $data['account_cert_pic3'];
        //
        $param['account_cert_pic4']          =  $data['account_cert_pic4'];
        //
        $param['agree_pic']                  = $data['agree_pic'];
        //子户用户姓名
        $jiami['message'] = $data['account_name'];
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['account_name'] = $res['data'];
        }else{
            $this->error('子户用户姓名加密失败');
        }
//        //子户商户法人身份证号|经营者身份证号
        $jiami['message'] = $data['account_cert_no'];
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['account_cert_no'] = $res['data'];
        }else{
            $this->error('经营者身份证号加密失败');
        }

        //子户商户法人手机号|经营者手机号
        $jiami['message'] = $data['account_phone'];
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['account_phone'] = $res['data'];
        }else{
            $this->error('手机号加密失败');
        }

        //企业名称全称
        $jiami['message'] = $data['enterprise_name'];
         $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['enterprise_name'] = $res['data'];
        }else{
            $this->error('企业名称加密失败');
        }

        //营业执照号
        $jiami['message'] = $data['business_license'];
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['business_license'] = $res['data'];
        } else{
            $this->error('营业执照号加密失败');
        }
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);
        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);
        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mgs/gateway.do";
        }else{
            $url = "http://filegate.yacolpay.com/filegs/gateway.do";
        }
        $res = $this->curlPost($url,$data);
        $res['request_no'] = $param['request_no'];
        $this->success('ok', $res);
    }

    /**
     * 修改
     *
     */
    public function sc_modify_merchant()
    {
        $data     = input('post.');
        $param    = $this->param;
        /****************业务参数***********************/
        $param['service']                    = "sc_modify_merchant";//服务名称
        $param['request_no']                 = Random::numeric(32);//入网请求号
        $param['split_member_id']            = $data['split_member_id'];
        $param['auth_protocol_no']           = Random::alnum(32);//用户授权协议流水号
        $param['auth_protocol_version']      = '1.0.0';//个人信息用户授权协议版本号，默认1.0.0
        //子户用户姓名
        if(!empty($data['account_name'])){
            $jiami['message'] = $data['account_name'];
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['account_name'] = $res['data'];
            }else{
                $this->error('子户用户姓名加密失败');
            }
        }

        //子户商户法人身份证号|经营者身份证号
        if(!empty($data['account_cert_no'])){
            $jiami['message'] = $data['account_cert_no'];
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['account_cert_no'] = $res['data'];
            }else{
                $this->error('经营者身份证号加密失败');
            }
        }


        //子户商户法人手机号|经营者手机号
        if(!empty($data['account_phone'])){
            $jiami['message'] = $data['account_phone'];
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['account_phone'] = $res['data'];
            }else{
                $this->error('手机号加密失败');
            }
        }


        //企业名称全称
        if(!empty($data['enterprise_name'])){
            $jiami['message'] = $data['enterprise_name'];
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['enterprise_name'] = $res['data'];
            }else{
                $this->error('企业名称加密失败');
            }
        }


//        //身份证正面
        $param['account_cert_pic1'] = $data['account_cert_pic1'];
//        $param['account_cert_pic1'] =  $this->img_url_to_base64($data['account_cert_pic1']);
////        $jiami['message'] =  $data['account_cert_pic1'];
//        $res = $this->json_post($this->jiami_url, $jiami);
//        if($res['code']==200){
//            $param['account_cert_pic1'] = $res['data'];
//        } else{
//            $this->error('身份证正面加密失败');
//        }
        //身份证反面
        $param['account_cert_pic2'] = $data['account_cert_pic2'];
//        $param['account_cert_pic2'] = $this->img_url_to_base64($data['account_cert_pic2']);
////        $jiami['message'] =  $data['account_cert_pic2'];
//        $res = $this->json_post($this->jiami_url, $jiami);
//        if($res['code']==200){
//            $param['account_cert_pic2']  = $res['data'];
//        }else{
//            $this->error('身份证反面加密失败');
//        }

        //营业执照图片
        $param['account_cert_pic3'] = $data['account_cert_pic3'];
//        $param['account_cert_pic3'] =  $this->img_url_to_base64($data['account_cert_pic3']);
////        $jiami['message'] =  $data['account_cert_pic3'];
//        $res = $this->json_post($this->jiami_url, $jiami);
//        if($res['code']==200){
//            $param['account_cert_pic3']  = $res['data'];
//        } else{
//            $this->error('营业执照图片加密失败');
//        }
        $param['account_cert_pic4'] = $data['account_cert_pic4'];
//        $param['account_cert_pic4'] =  $this->img_url_to_base64($data['account_cert_pic4']);
////        $jiami['message'] =  $data['account_cert_pic4'];
//        $res = $this->json_post($this->jiami_url, $jiami);
//        if($res['code']==200){
//            $param['account_cert_pic4']  = $res['data'];
//        } else{
//            $this->error('协议影印件加密失败');
//        }
        $param['agree_pic'] = $data['agree_pic'];
//        $param['agree_pic'] = $this->img_url_to_base64($data['agree_pic']);
//        $jiami['message'] = $data['agree_pic'];
//        $res = $this->json_post($this->jiami_url, $jiami);
//        if($res['code']==200){
//            $param['agree_pic']  = $res['data'];
//        }
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);
        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);
        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mgs/gateway.do";
        }else{
            $url = "http://filegate.yacolpay.com/filegs/gateway.do";
        }

        $res = $this->curlPost($url,$data);
        $res['request_no'] = $param['request_no'];
        $this->success('ok', $res);
    }

    /**
     * 子账号查询
     */

    public function sc_query_merchant(){
        $data                         = input('post.');
        $param                        = $this->param;
        $param['service']             = "sc_query_merchant";
        $param['request_no']          = $data['request_no'];
        $param['split_member_id']     = $data['split_member_id'];
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);

        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mgs/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mgs/gateway.do";
        }
        $res = $this->curlPost($url,$data);
        if(!empty($res['splitMerchants'][0])){

            if(!empty($res['splitMerchants'][0]['account_name'])){
                $jiemi['message'] = $res['splitMerchants'][0]['account_name'];
                $jiemi_arr = $this->json_post($this->jiemi_url, $jiemi);
                if($jiemi_arr['code']==200){
                    $res['splitMerchants'][0]['account_name'] = $jiemi_arr['data'];
                }
            }

            if(!empty($res['splitMerchants'][0]['account_cert_no'])){
                $jiemi['message'] = $res['splitMerchants'][0]['account_cert_no'];
                $jiemi_arr = $this->json_post($this->jiemi_url, $jiemi);
                if($jiemi_arr['code']==200){
                    $res['splitMerchants'][0]['account_cert_no'] = $jiemi_arr['data'];
                }
            }

            if(!empty($res['splitMerchants'][0]['account_phone'])){
                $jiemi['message'] = $res['splitMerchants'][0]['account_phone'];
                $jiemi_arr = $this->json_post($this->jiemi_url, $jiemi);
                if($jiemi_arr['code']==200){
                    $res['splitMerchants'][0]['account_phone'] = $jiemi_arr['data'];
                }
            }

            if(!empty($res['splitMerchants'][0]['enterprise_name'])){
                $jiemi['message'] = $res['splitMerchants'][0]['enterprise_name'];
                $jiemi_arr = $this->json_post($this->jiemi_url, $jiemi);
                if($jiemi_arr['code']==200){
                    $res['splitMerchants'][0]['enterprise_name'] = $jiemi_arr['data'];
                }
            }

            if(!empty($res['splitMerchants'][0]['business_license'])){
                $jiemi['message'] = $res['splitMerchants'][0]['business_license'];
                $jiemi_arr = $this->json_post($this->jiemi_url, $jiemi);
                if($jiemi_arr['code']==200){
                    $res['splitMerchants'][0]['business_license'] = $jiemi_arr['data'];
                }
            }
        }
        if(!empty($res['splitMerchants'][0]['status'])){
            if($res['splitMerchants'][0]['status']=="NORMAL"){
                $res['splitMerchants'][0]['status'] = "正常";
            }else{
                $res['splitMerchants'][0]['status'] = "非正常";
            }

        }
        $this->success('ok', $res['splitMerchants'][0]);
    }



    /**
     * 账户余额查询
     */

    public function sc_query_balance(){
        $param                        = $this->param;
        $param['service']             = "sc_query_balance";
        $param['split_member_id']     = input('split_member_id');
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);


        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mgs/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mgs/gateway.do";
        }

        $res = $this->curlPost($url,$data);
        $this->success('ok', $res);
    }

    /**
     * 收款
     */
    public function b2b_sk(){
        $param                          = $this->param;
        $param['service']               = "b2b_sk";
        $param['out_trade_no']          = date('Ymd',time()).uniqid();//商户网站交易订单号，商户内部保证唯一
        $param['seller_identity_id']    = input('split_member_id');
        $param['seller_identity_type']  = 'MEMBER_ID';
        $param['amount']                = input('post.amount');//金额
        $param['product_desc']          = input('post.product_desc');//商品描述
        $param['extend_param']          = 'name^'.input('post.extend_param');//扩展
        $param['device_id']             = Random::uuid();//设备号
        $param['pay_method']            = "online_bank^".$param['amount']."^".input('post.yinhang').",DEBIT,B";
        $param['device_typ']            = input('post.device_typ');//设备号;
        $param['mac_address']           = '127.0.0.1';
        $param['auth_protocol_no']      = Random::numeric(32);
        $param['auth_protocol_version'] = "1.0.0";//用户授权协议版本号
        if(input('post.split_trade_type')){
            $param['split_trade_type']      = input('post.split_trade_type');//1-按固定金额，2-比例
        }
        $param['split_party']           = input('post.split_party');//分账方会员ID
        if(input('post.split_trade_amount')){
            $param['split_trade_amount']    = input('post.split_trade_amount');//分账金额
        }
        if(input('post.split_trade_ratio')){
            $param['split_trade_ratio']     = input('post.split_trade_ratio');//分账比例
        }


        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);



        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mas/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mas/gateway.do";
        }


        $res = $this->curlPost($url,$data,2);
        $tiao = json_decode($res,true);
        if(!$tiao){
            $str = $res;
            file_put_contents('pay.html',$str);
            $url = "https://".$_SERVER['HTTP_HOST'].'/pay.html';
            $this->success('ok', $url);
        }else{
            $this->success('ok', $tiao);
        }

    }

    /**
     * 交易查询（对账查询）
     */

    public function query_b2c_order(){
        $param                   = $this->param;
        $param['service']        = "query_b2c_order";
        $param['start_time']     = input('start_time');
        $param['end_time']       = input('end_time');
        $param['page_no']        = input('page_no',1);
        $param['page_size']      = input('page_size',20);
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);



        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mas/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mgs/gateway.do";
        }

        $res = $this->curlPost($url,$data);
        $this->success('ok', $res);
    }

    /**
     * 子户代付
     */
    public function account_book_single_pay2bank(){
        $param                          = $this->param;
        $param['service']               = "account_book_single_pay2bank";
        $param['out_trade_no']          = date('Ymd',time()).uniqid();//商户网站交易订单号，商户内部保证唯一
        $param['split_party_id']        = input('split_member_id');
        $jiami['message'] = input('post.bank_card_no');
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['bank_card_no']  = $res['data'];
        }
        $jiami['message'] = input('post.account_name');
        $res = $this->json_post($this->jiami_url, $jiami);
        if($res['code']==200){
            $param['account_name']  = $res['data'];
        }
        $param['bank_name']             = input('post.bank_name');//开户银行
        $param['bank_code']             = input('post.bank_code');//银行代码
        $param['card_type']             = input('post.card_type');//卡类型
        $param['card_attribute']        = input('post.card_attribute');//卡属性
        $param['amount']                = input('post.amount');//金额
        $param['summary']               = input('post.summary');//摘要
        $param['auth_protocol_no']      = Random::numeric(32);
        $param['auth_protocol_version'] = "1.0.0";//用户授权协议版本号
        $param['product_desc']          = input('post.product_desc');//商品描述
        $param['extend_param']          = 'name^'.input('post.extend_param');//扩展
        $param['device_id']             = Random::uuid();//设备号
        $param['pay_method']            = "online_bank^".$param['amount']."^".input('post.yinhang').",DEBIT,B";
        $param['device_typ']            = input('post.device_typ');//设备号;
        $param['mac_address']           = '127.0.0.1';
        $param['split_trade_type']      = input('post.split_trade_type');//1-按固定金额，2-比例
        $param['split_party']           = input('post.split_party');//分账方会员ID
        $param['split_trade_amount']    = input('post.split_trade_amount');//分账金额
        $param['split_trade_ratio']     = input('post.split_trade_ratio');//分账比例

        if($this->type==2){
            $jiami['message'] = input('post.id_card_num');
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['id_card_num']  = $res['data'];
            }
            $jiami['message'] = input('post.phone_no');
            $res = $this->json_post($this->jiami_url, $jiami);
            if($res['code']==200){
                $param['phone_no']  = $res['data'];
            }
        }
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);

        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mas/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mgs/gateway.do";
        }

        $res = $this->curlPost($url,$data);
        $this->success('ok', $res);
    }


    /**
     * 子户代付查询
     */
    public function agent_query_single_pay2bank(){
        $param                   = $this->param;
        $param['service']        = "agent_query_single_pay2bank";
        $param['out_trade_no']      = input('out_trade_no',20);
        ksort($param);
        $sign = $this->getSignMsg($param,$this->charset);

        //签名
        $jiami['message'] = $sign;
        $res = $this->json_post($this->qianmi_url, $jiami);
        if($res['code']==200){
            $param['sign'] = $res['data'];
        }
        $data = $this->createcurl_data($param);
        if($this->type==2){
            $url = "http://test.gate.yacolpay.com/mas/gateway.do";
        }else{
            $url = "http://gate.yacolpay.com/mgs/gateway.do";
        }
        $res = $this->curlPost($url,$data);
        $this->success('ok', $res);
    }


    /**
     * @param $url
     * @param $data
     * @return mixed
     */

    public  function curlPost($url, $data,$type=1) {

        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_POST, 1 );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        $data = curl_exec ( $ch );
        curl_close ( $ch );
        //由于json转数组使用了json_decode所以需要将非UTF-8的内容强转为UTF-8字符集
        //return mb_convert_encoding(urldecode($data),"UTF-8");
        if($type==1){
            $data = urldecode($data);
            return json_decode($data,true);
        }else{
            return $data;
        }
    }

    /**
     * [createcurl_data 拼接模拟提交数据]
     *
     * @param array $pay_params
     * @return string url格式字符
     */
    public  function createcurl_data($pay_params = array()) {
        $params_str = "";
        foreach ( $pay_params as $key => $val ) {
            if (isset ( $val ) && ! is_null ( $val ) && @$val != "") {
                $params_str .= "&" . $key . "=" . urlencode ( urlencode ( trim ( $val ) ) );
            }
        }
        if ($params_str) {
            $params_str = substr ( $params_str, 1 );
        }
        return $params_str;
    }


    public function json_post($url, $data = NULL)
    {
        $data['charset'] = $this->charset;
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        $arr = json_decode($res,true);
        return $arr;
    }

    /**
     * getSignMsg 计算签名
     * @param array $pay_params
     *        	计算签名数据
     * @param string $sign_type
     *        	签名类型
     * @return string $signMsg 返回密文
     */

    public function getSignMsg($pay_params = array(),$_input_charset) {
        $params_str = "";
        foreach ( $pay_params as $key => $val ) {
            if ($key != "sign" && $key != "sign_type" && $key != "sign_version" && isset ( $val ) && @$val != "") {
                $params_str .= $key . "=" . $val . "&";
            }
        }
        $params_str = substr ( $params_str, 0, - 1 );
        $params_str=mb_convert_encoding($params_str,$_input_charset);
        return $params_str;
    }



}
